package com.ruoyi.SpringWebSocket;

import com.ruoyi.agent.domain.SysAgent;
import com.ruoyi.agent.mapper.SysAgentMapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.messages.domain.SysNotify;
import com.ruoyi.store.domain.SysStore;
import com.ruoyi.store.mapper.SysStoreMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Author: 吕宇宏
 * @Date: 2024/6/26 11:33
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class MyWsHandler extends AbstractWebSocketHandler {



    private final SysUserMapper userMapper;


    private final SysStoreMapper storeMapper;


    private final SysAgentMapper agentMapper;



   public static Map<String,SessionBeans> sessionBeansMap = new ConcurrentHashMap<>();

//    public static StringBuffer msg = new StringBuffer();  //线程安全的String类型

    //建立连接后
    @Override
    public void afterConnectionEstablished(WebSocketSession session )throws Exception {
        super.afterConnectionEstablished(session);


        Long userId = (Long) session.getAttributes().get("userId");
        SessionBeans sessionBeans = new SessionBeans(userId, session);
        sessionBeansMap.put(session.getId(),sessionBeans);
        log.info("已将用户：{},添加进map中",sessionBeans.getUserId());
//        msg.append("用户id:"+sessionBeans.getUserId()+"——已进入聊天\n");
//        sendmsg(sessionBeansMap);

    }



    //接受消息后
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        super.handleTextMessage(session, message);
        log.info("接收到:{},的消息：{}",sessionBeansMap.get(session.getId()).getUserId(),message.getPayload());
//        msg.append("用户id:"+sessionBeansMap.get(session.getId()).getUserId()+":"+message.getPayload()+"\n");
//        sendmsg(sessionBeansMap);
    }

    //发生异常时
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        super.handleTransportError(session, exception);
        if (session.isOpen()) {
            session.close();
            log.info("session:{}发生异常，强制关闭",sessionBeansMap.get(session.getId()).getUserId());
        }
        log.info("session:{}发生异常",sessionBeansMap.get(session.getId()).getUserId());
//        sendmsg(sessionBeansMap);

    }


    //连接断开后
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        super.afterConnectionClosed(session, status);
//        Long userId = sessionBeansMap.get(session.getId()).getUserId();
        log.info("用户id:{}断开连接，删除对应的map",sessionBeansMap.get(session.getId()).getUserId());
        sessionBeansMap.remove(session.getId());
//        msg.append("用户id:"+userId+"——退出聊天\n");
//        sendmsg(sessionBeansMap);

    }



//    @Scheduled(fixedDelay = 2000)
//    public void schedulesendMsg() {
//
//        sessionBeansMap.keySet().stream().forEach(key ->{
//            try {
//                sessionBeansMap.get(key).getSession().sendMessage(new TextMessage("心跳/每两秒一次"));
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        });
//    }

//    public void sendmsg(Map<String,SessionBeans> sessionBeansMap) {
//        sessionBeansMap.keySet().stream().forEach(key -> {
//            try {
//                sessionBeansMap.get(key).getSession().sendMessage(new TextMessage(msg));
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        });
//    }
//
//    public void sendmsgBy(Map<String,SessionBeans> sessionBeansMap,String msgs) {
//        sessionBeansMap.keySet().stream().forEach(key -> {
//            try {
//                sessionBeansMap.get(key).getSession().sendMessage(new TextMessage(msgs));
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        });
//    }

    //處理具體的消息通知業務
    public void sendNotify(SysNotify sysNotify) {
        String type = sysNotify.getType();
        if (type.equals("0")||type=="0") {
            //證明是商家餘額不足造成的通知

            //根据dataid 查询对应的商铺名称：
            SysStore sysStore = storeMapper.selectSysStoreById(sysNotify.getDataId());



            Set<Long> userIds = getSameUserIds(sysNotify);


            Map<String, SessionBeans> userSession = getUserSession(userIds);
            //遍历当前用户会话发送信息：
            userSession.keySet().stream().forEach(key->{
                try {
                    userSession.get(key).getSession().sendMessage(new TextMessage("商铺:"+sysStore.getName()+",当前余额为:"+sysStore.getBalance()+",请及时充值"));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
        else  if (type.equals("1")||type=="1") {
            Set<Long> userIds = getSameUserIds(sysNotify);
            Map<String, SessionBeans> userSession = getUserSession(userIds);
            //遍历当前用户会话发送信息：
            userSession.keySet().stream().forEach(key->{
                try {
                    userSession.get(key).getSession().sendMessage(new TextMessage("商家下单背调订单"));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
        else  if (type.equals("2")||type=="2") {
            Set<Long> userIds = getSameUserIds(sysNotify);
            Map<String, SessionBeans> userSession = getUserSession(userIds);
            //遍历当前用户会话发送信息：
            userSession.keySet().stream().forEach(key->{
                try {
                    userSession.get(key).getSession().sendMessage(new TextMessage("商家下单批量订单"));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
        else  if (type.equals("3")||type=="3") {
            Set<Long> userIds = getStoreUserIds(sysNotify);
            Map<String, SessionBeans> userSession = getUserSession(userIds);
            //遍历当前用户会话发送信息：
            userSession.keySet().stream().forEach(key->{
                try {
                    userSession.get(key).getSession().sendMessage(new TextMessage("候选人授权"));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
        else  if (type.equals("4")||type=="4") {
            Set<Long> userIds = getStoreUserIds(sysNotify);
            Map<String, SessionBeans> userSession = getUserSession(userIds);
            //遍历当前用户会话发送信息：
            userSession.keySet().stream().forEach(key->{
                try {
                    userSession.get(key).getSession().sendMessage(new TextMessage("线上调查报告已出"));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
    }

    private Set<Long> getSameUserIds(SysNotify sysNotify) {
        Long deptId = sysNotify.getDeptId();
        //查詢對應部門的的所有用户
        List<SysUser> sysUsers= userMapper.selectByDeptId(deptId);
        Set<Long> userIds = sysUsers.stream().map(SysUser::getUserId).collect(Collectors.toSet());

        //查詢對應商鋪的代理商
        //根據商鋪部門id查詢對應的商品對象，根據商鋪對象獲取對於的代理商id
        List<SysStore> sysStores= storeMapper.selectSysStoreByDeptId(deptId);
        if (!CollectionUtils.isEmpty(sysStores)) {
            Long agentId = sysStores.get(0).getAgentId();
            if (agentId==0) {
                //说明是管理端的,查询所有的管理的用户
                List<SysUser> sysUsers1 = userMapper.selectByDeptId(100l);
                Set<Long> collect = sysUsers1.stream().map(SysUser::getUserId).collect(Collectors.toSet());
                userIds.addAll(collect);
            }else {
                SysAgent sysAgent = agentMapper.selectSysAgentById(agentId);
                Long AgentDeptId = sysAgent.getDeptId();
                //通过部门id查询所有的代理商用户
                List<SysUser> agentUsers =userMapper.selectByDeptId(AgentDeptId);
                Set<Long> agentUsersIds = agentUsers.stream().map(SysUser::getUserId).collect(Collectors.toSet());
                userIds.addAll(agentUsersIds);
            }


        }
        return userIds;
    }

    private Set<Long> getStoreUserIds(SysNotify sysNotify) {
        Long deptId = sysNotify.getDeptId();
        //查詢對應部門的的所有用户
        List<SysUser> sysUsers= userMapper.selectByDeptId(deptId);
        Set<Long> userIds = sysUsers.stream().map(SysUser::getUserId).collect(Collectors.toSet());

        return userIds;
    }

    public Map<String,SessionBeans> getUserSession(Set<Long> userIds) {
        ConcurrentHashMap<String,SessionBeans> newSessionMap = new ConcurrentHashMap<>();
        sessionBeansMap.keySet().stream().forEach(key->{

            if (userIds.contains(sessionBeansMap.get(key).getUserId())) {
                //如果当前登录用户中存在
                newSessionMap.put(key,sessionBeansMap.get(key));
            }


        });
        return newSessionMap;

    }
}
